/*
 * Copyright 2013-2018 Lilinfeng.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.jeecg.netty.sensor.nettyserver;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.jeecg.glr.service.IGlrSensorService;
import org.jeecg.netty.config.NettyConfig;
import org.jeecg.netty.sensor.decode.SenSorDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.FixedRecvByteBufAllocator;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;

/**
 *
 * <p>
 * Description: [描述该类概要功能介绍]
 * </p>
 *
 * @author <a href="mailto: xiebin@gaotai.cn">作者中文名</a>
 * @version $Revision$
 */
@Component
public class SensorNettyServer extends Thread
{

	private static final Logger logger = LoggerFactory.getLogger(SensorNettyServer.class);

	private final static int readerIdleTimeSeconds = 300;//读操作空闲180秒

	private final static int writerIdleTimeSeconds = 300;//写操作空闲180秒

	private final static int allIdleTimeSeconds = 300;//读写全部空闲180秒

	@Resource private NettyConfig nettyConfig;

	@Resource private SensorNettyServerHandler ledNettyServerHandler;

	@Resource
	IGlrSensorService glrSensorService;

	@PostConstruct
	public void init()
	{
		glrSensorService.intiSenSorAll();
		this.start();
	}

	@Override
	public void run()
	{
		// 配置服务端的NIO线程组
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try
		{
			//创建 ServerBootstrap 实例来引导绑定和启动服务器
			ServerBootstrap b = new ServerBootstrap();
			// NioEventLoopGroup 来接受和处理新连接，指定通道类型为 NioServerSocketChannel
			//指定 InetSocketAddress，服务器监听此端口
			b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
					//队列大小
					.option(ChannelOption.SO_BACKLOG, 1024)
					//是禁止使用Nagle算法
					.option(ChannelOption.TCP_NODELAY, true)
					//.option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(1024, 2048, 65536))
					.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(1024))
					.childHandler(new ChildChannelHandler());//添加一个 ChannelHandler，客户端成功连接服务器后就会被执行

			// 绑定端口，同步等待成功
			ChannelFuture f = b.bind(nettyConfig.getSensorIp(), nettyConfig.getSensorPort()).sync();
			System.out.println("------------Sensor------server start-----------------");
			// 等待服务端监听端口关闭
			f.channel().closeFuture().sync();
		}
		catch (Exception e)
		{
			logger.error("服务启动异常:", e);
			e.printStackTrace();
		}
		finally
		{
			// 优雅退出，释放线程池资源
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}

	/**
	 *
	 * <p>
	 * 添加一个 ChannelHandler，客户端成功连接服务器后就会被执行
	 * </p>
	 *
	 * @author <a href="mailto: xiebin@54604344@qq.com">xiebin</a>
	 * @version $Revision$
	 */
	private class ChildChannelHandler extends ChannelInitializer<SocketChannel>
	{
		@Override
		protected void initChannel(SocketChannel arg0) throws Exception
		{
			//判断客户端是否断开
			arg0.pipeline().addLast("idleStateHandler",
				new IdleStateHandler(readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds));
			//arg0.pipeline().addLast(new LightDecoder());
			arg0.pipeline().addLast(new SenSorDecoder());
			// 以下两行代码为了解决半包读问题LineBasedFrameDecoder、StringDecoder
			//arg0.pipeline().addLast(new LineBasedFrameDecoder(1024));
			//arg0.pipeline().addLast(new StringDecoder());
            //设置字符串形式的解码
            arg0.pipeline().addLast(ledNettyServerHandler);
			arg0.pipeline().addLast(new ChannelInboundHandlerAdapter(){
				@Override
				public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception
				{
					if(IdleStateEvent.class.isAssignableFrom(evt.getClass()))
					{
						IdleStateEvent event = (IdleStateEvent) evt;

						//如果在3分钟内没有发送心跳包，表示已经掉线
						if(event.state() == IdleState.ALL_IDLE)
						{
							glrSensorService.removeOffLineGataWay(ctx);
						}
					}
				}
			});

		}

	}

	/**
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception
	{
		//new NettyServer().bind(Constants.IP, Constants.PORT);

	}
}
